const mongoose = require('mongoose')
const UserSchema = mongoose.model('UserSchema')
const Router = require('koa-router')
const UserRouter = new Router()
const { generateCaptcha, CaptchaMode } = require('@tuzhanai/captcha')

function setCookie (ctx, name) {
  ctx.cookies.set(
    'name', name, {
        path: '/',       // 写cookie所在的路径，‘/’代表在根路径
        maxAge: 1000 * 60 * 60,   // cookie有效时长ms， 60minutes
        httpOnly: false,  // 是否只用于http请求中获取
        overwrite: false  // 同名cookie是否允许重写
    }
  )
}

// 查找用户是否已经注册
async function getUser (userName) {
  const user = await UserSchema.findOne({ userName }).exec()
  return user
}

UserRouter.post('/login', async ctx => {
  const { body } = ctx.request
  try {
    if (global.captchaText.toLocaleLowerCase() !== body.captcha.toLocaleLowerCase()) {
     return ctx.body = {
       code: 500,
       message: '验证码不正确'
     }
    }
    const user = await getUser(body.userName)
    if (user) {
      if (user.password === body.password) {
        // 设置session
        setCookie(ctx, body.userName)
        ctx.body = {
          code: 200,
          message: '登录成功'
        }
      } else {
        // 密码不正确
        ctx.body = {
          code: 500,
          message: '密码不正确'
        }
      }
    } else {
      ctx.body = {
        code: 500,
        message: '该用户还未注册'
      }
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '登录失败'
    }
  }
})

UserRouter.post('/register', async ctx => {
  const { body } = ctx.request
  try {
    const user = await getUser(body.userName)
    if (user) {
      return ctx.body = {
        code: 500,
        message: '该用户名已经被注册，请重新选择'
      }
    }
    await new UserSchema(body).save()
    // 设置session
    setCookie(ctx, body.userName)
    ctx.body = {
      code: 200,
      message: '注册成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '注册失败'
    }
  }
})

UserRouter.post('/logout', async ctx => {
  try {
    ctx.cookies.set('name', undefined, { maxAge: 0 })
    ctx.body = {
      code: 200,
      message: '退出成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '退出失败'
    }
  }
})

UserRouter.get('/captcha', ctx => {
  try {
    const { text, data } = generateCaptcha(CaptchaMode.Medium)
    // 在不同的路由之间设置变量
    global.captchaText = text
    // buffer可以通过toString()转换为base64码
    const base64 = data.toString('base64')
    ctx.body = {
      code: 200,
      message: `data:image/png;base64,${base64}`
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '获取验证码失败'
    }
  }
})

module.exports = UserRouter